import logging
import requests
from audio_pkg.models.configdata import APIConfig

logger = logging.getLogger(__name__)

class GetAccessToken:
    def __init__(self,api_config:APIConfig):
        self.api_config = api_config
        self.params = {
            "grant_type": "client_credentials",
            "client_id": self.api_config.API_KEY,
            "client_secret": self.api_config.SECRET_KEY
        }

        self.token = None
        self.request_token() 

    def request_token(self): 

        """请求并保存 access_token，增强错误处理逻辑"""
        try:
            response = requests.post(
                url=self.api_config.TOKEN_URL,
                params=self.params,
                timeout=10
            )
            
            # 强制尝试解析JSON（无论HTTP状态码）
            try:
                response_data = response.json()
            except ValueError:
                logger.error("响应内容不是有效的JSON格式")
                return

            # 先检查是否存在错误信息
            if "error" in response_data:
                error_desc = response_data.get("error_description", "未知错误")
                
                if error_desc == "unknown client id":
                    logger.error("API Key 错误: 未知的客户端ID")
                elif error_desc == "Client authentication failed":
                    logger.error("Secret Key 错误: 客户端认证失败")
                else:
                    logger.error(f"认证服务返回未处理的错误类型: {error_desc}")
                
                return  # 发现错误后提前返回

            # 再检查access_token是否存在
            
            self.token = response_data.get("access_token")
            if not self.token:
                logger.error("响应中缺少access_token字段")
                raise ValueError("access_token缺失")

            # 最后验证HTTP状态码
            response.raise_for_status()

        except requests.exceptions.Timeout:
            logger.error("请求超时，无法连接认证服务器")
        except requests.exceptions.HTTPError as e:
            logger.error(f"HTTP协议错误: {e}")
        except requests.exceptions.RequestException as e:
            logger.error(f"网络请求异常: {e}")
        except Exception as ex:
            logger.error(f"未捕获的异常: {ex}")

    def back_token(self):
        """返回token并添加状态检查"""
        if self.token is None:
            logger.error("尝试使用未初始化的token")
            raise RuntimeError("请先调用request_token获取token")
        return self.token